<template>
  <div class="orgManagement-container ">
    <v-card class="pa-4 elevation-0 rounded-lg">
      <v-card-title>
        <v-btn v-if="$perms('system_org_insert')
          && null != userInfo && (userInfo.izSuperAdmin || userInfo.dataScope === '3')
        " color="primary" @click="handleInsert">
          <v-icon start>mdi-plus</v-icon>
          添加
        </v-btn>
      </v-card-title>

      <v-card-text elevation="10" class="">
        <v-data-table ref="tableTreeData" rounded="lg" elevation="10" v-model:expanded="expanded" :headers="headers"
          :items="data" :loading="listLoading" :items-per-page="-1" class="elevation-9 rounded-lg" item-value="id"
          item-children="children" :item-selectable="() => false" :load-children="loadNode">
          <!-- 机构唯一编号 -->
          <template v-slot:item.orgCode="{ item }">
            {{ item.orgCode }}
          </template>

          <!-- 机构名称 -->
          <template v-slot:item.orgName="{ item }">
            {{ item.orgName }}
          </template>

          <!-- 排序 -->
          <template v-slot:item.sortNo="{ item }">
            {{ item.sortNo }}
          </template>

          <!-- 备注 -->
          <template v-slot:item.remark="{ item }">
            {{ item.remark }}
          </template>

          <!-- 操作 -->
          <template v-slot:item.actions="{ item }"
            v-if="$perms('system_org_insert') || $perms('system_org_update') || $perms('system_org_delete')">
            <div class="d-flex gap-2">
              <v-btn v-if="$perms('system_org_update')" variant="text" size="small" color="primary"
                @click="handleUpdate(item)">
                编辑
              </v-btn>

              <v-menu>
                <template v-slot:activator="{ props }">
                  <v-btn variant="text" size="small" v-bind="props">
                    更多
                    <v-icon end>mdi-chevron-down</v-icon>
                  </v-btn>
                </template>
                <v-list>
                  <v-list-item v-if="$perms('system_org_insert')" @click="handleInsertByParent(item)">
                    <v-list-item-title>添加下级</v-list-item-title>
                  </v-list-item>
                  <v-list-item v-if="$perms('system_org_delete')" @click="handleDelete(item)">
                    <v-list-item-title>删除</v-list-item-title>
                  </v-list-item>
                </v-list>
              </v-menu>
            </div>
          </template>
        </v-data-table>
      </v-card-text>
    </v-card>

    <edit ref="edit" @refreshNodeBy="refreshNodeBy"></edit>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, getCurrentInstance } from 'vue';
import { getTreeLazy, doDelete } from "@/api/system/org/orgManagement";
import { useAuthStore } from "@/stores/auth";
import { useMessage } from "@/composables/useMessage";
import Edit from "./components/OrgManagementEdit.vue";
import { isNull } from "@/utils/validate";
import type { UserInfoResponse } from "@/api/user";

const { proxy } = getCurrentInstance()!;
const authStore = useAuthStore();
const { error: showError, success: showSuccess } = useMessage();

let userInfo = ref<UserInfoResponse>();
const dict = ref<any>({});
const defaultNode = "0";
const tmpTreeData = ref<Record<string, any>>({});
const data = ref([]);
const expanded = ref([]);
const listLoading = ref(true);
const edit = ref<{ showEdit: (row?: any) => void }>();

const headers = [
  { title: '机构唯一编号', key: 'orgCode', minWidth: '200px' },
  { title: '机构名称', key: 'orgName', minWidth: '150px' },
  { title: '排序', key: 'sortNo' },
  { title: '备注', key: 'remark' },
  { title: '操作', key: 'actions', align: 'end' }
];

onMounted(async () => {
  if (proxy) {
    dict.value = {
      org_type: proxy.$getDictList("org_type"),
      no_yes: proxy.$getDictList("no_yes"),
    };
  }
  await getCurrUser();
  await fetchData();
});

const handleInsert = () => {
  edit.value?.showEdit();
};

const handleInsertByParent = (row: any) => {
  if (row.id) {
    if (row.parentIds.split(",").length > 3) {
      showError("组织树深度最大支持4层");
      return;
    }

    let rowTmp: any = {};
    rowTmp.parentId = row.id;
    rowTmp.parentName = row.orgName;
    rowTmp.parentCode = row.orgCode;

    edit.value?.showEdit(rowTmp);
  }
};

const handleUpdate = (row: any) => {
  if (row) {
    edit.value?.showEdit(row);
  }
};

const handleDelete = async (row: any) => {
  if (row.id) {
    // TODO: 需要实现 $baseConfirm 确认对话框
    const confirmed = confirm("你确定要删除当前项吗");
    if (confirmed) {
      try {
        const response = await doDelete({ id: row.id });
        showSuccess(response.data?.msg || "删除成功");
        await fetchData();
      } catch (error) {
        showError("删除失败");
      }
    }
  }
};

const fetchData = async () => {
  listLoading.value = true;
  const { data: responseData } = (await getTreeLazy({ parentId: defaultNode }));
  data.value = responseData;
  setTimeout(() => {
    listLoading.value = false;
  }, 300);
};

const refreshNodeBy = (id: any) => {
  if (isNull(tmpTreeData.value[id])) {
    fetchData();
  } else {
    let tree = tmpTreeData.value[id].tree;
    let treeNode = tmpTreeData.value[id].treeNode;
    let resolve = tmpTreeData.value[id].resolve;
    loadNode(tree, treeNode, resolve);
  }
};

const loadNode = async (tree: any, treeNode: any, resolve: any) => {
  const { data: responseData } = await getTreeLazy({ parentId: tree.id });
  if (!responseData || responseData.length === 0) {
    // TODO: 需要实现 $baseEventBus 事件总线
    // $baseEventBus.$emit("reloadRouterView");
    console.log("需要重新加载路由视图");
    return;
  }
  tmpTreeData.value[tree.id] = { tree, treeNode, resolve };
  resolve(responseData);
};

const getCurrUser = async () => {
  listLoading.value = true;

  userInfo.value = authStore.userInfo;
  setTimeout(() => {
    listLoading.value = false;
  }, 300);
};
</script>

<style scoped>
.orgManagement-container {
  padding: 0px;
}
</style>
